use ratatui::{
    prelude::*,
    widgets::*,
};
use crate::app::{App, Status};

pub fn render(frame: &mut Frame, app: &App) {
    let chunks = Layout::default()
        .direction(Direction::Vertical)
        .constraints([
            Constraint::Length(3),      // 标题
            Constraint::Length(3),      // 网络信息
            Constraint::Min(10),        // IP列表
            Constraint::Length(6),      // 消息区域
            Constraint::Length(3),      // 命令输入框
        ])
        .split(frame.size());

    render_title(frame, chunks[0]);
    render_network_info(frame, app, chunks[1]);
    render_ip_list(frame, app, chunks[2]);
    render_message(frame, app, chunks[3]);
    render_input(frame, app, chunks[4]);
}

fn render_title(frame: &mut Frame, area: Rect) {
    let title = Paragraph::new("IP Scanner")
        .alignment(Alignment::Center)
        .block(Block::default().borders(Borders::ALL));
    frame.render_widget(title, area);
}

fn render_network_info(frame: &mut Frame, app: &App, area: Rect) {
    let network_info = format!("Current Network: {}", app.network);
    let network_widget = Paragraph::new(network_info)
        .alignment(Alignment::Center)
        .block(Block::default().borders(Borders::ALL));
    frame.render_widget(network_widget, area);
}

fn render_ip_list(frame: &mut Frame, app: &App, area: Rect) {
    let mut text = Vec::new();
    let mut spans = Vec::new();
    
    for (i, ip) in app.ip_addresses.iter().enumerate() {
        // 根据状态设置颜色
        let style = match &ip.status {
            Status::Unknown => Style::default().fg(Color::DarkGray),
            Status::Pending => Style::default().fg(Color::White),
            Status::Success(latency) => {
                if *latency < 10 {
                    Style::default().fg(Color::Green)
                } else if *latency < 50 {
                    Style::default().fg(Color::Rgb(100, 255, 100))
                } else if *latency < 100 {
                    Style::default().fg(Color::Rgb(150, 255, 50))
                } else if *latency < 500 {
                    Style::default().fg(Color::Rgb(200, 255, 0))
                } else {
                    Style::default().fg(Color::Rgb(255, 165, 0))
                }
            },
            Status::Timeout => Style::default().fg(Color::Red),
        };

        // 只显示 IP 地址，用颜色区分状态
        spans.push(Span::styled(
            format!("{:<17}", ip.address), // 17 = 15(IP长度) + 2(空格)
            style
        ));
        
        // 每10个IP换一行
        if (i + 1) % 10 == 0 {
            text.push(Line::from(spans));
            spans = Vec::new();
        }
    }

    // 处理最后一行
    if !spans.is_empty() {
        text.push(Line::from(spans));
    }

    let ip_list = Paragraph::new(text)
        .block(Block::default().title("IP Addresses").borders(Borders::ALL));
    frame.render_widget(ip_list, area);
}

fn render_message(frame: &mut Frame, app: &App, area: Rect) {
    let message = if app.scanning {
        format!(
            "Progress: {:.1}%\n{}",
            app.progress_ratio() * 100.0,
            app.message
        )
    } else if app.message.contains("颜色说明") {
        let mut colored_text = Vec::new();
        // 先添加标题
        colored_text.push(Line::from("颜色说明:"));
        
        // 直接构建颜色图例，而不是解析消息文本
        let legends = [
            (Color::Green, "绿色", "延迟 < 10ms"),
            (Color::Rgb(100, 255, 100), "浅绿色", "延迟 < 50ms"),
            (Color::Rgb(150, 255, 50), "黄绿色", "延迟 < 100ms"),
            (Color::Rgb(200, 255, 0), "黄色", "延迟 < 500ms"),
            (Color::Rgb(255, 165, 0), "橙色", "延迟 < 600ms"),
            (Color::Red, "红色", "超时"),
            (Color::DarkGray, "灰色", "未扫描"),
        ];

        for (color, name, desc) in legends {
            colored_text.push(Line::from(vec![
                Span::styled("  ", Style::default().fg(color)),
                Span::styled(name, Style::default().fg(color)),
                Span::raw(format!("     - {}", desc))
            ]));
        }

        return frame.render_widget(
            Paragraph::new(colored_text)
                .scroll((app.message_scroll, 0))
                .block(Block::default()
                    .title("Message [↑↓/j/k to scroll]")
                    .borders(Borders::ALL)),
            area
        );
    } else {
        app.message.clone()
    };

    let message_widget = Paragraph::new(message)
        .scroll((app.message_scroll, 0))
        .block(Block::default()
            .title("Message [↑↓/j/k to scroll]")
            .borders(Borders::ALL));
    
    frame.render_widget(message_widget, area);
}

fn render_input(frame: &mut Frame, app: &App, area: Rect) {
    let input = Paragraph::new(app.input.as_str())
        .block(Block::default().title("Command").borders(Borders::ALL));
    frame.render_widget(input, area);
} 